package com.sec.android.app.myfiles.fragment.home;

import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.TextView;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.activity.FileListActivity;
import com.sec.android.app.myfiles.feature.CloudMgr;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.info.AppConstants.StoragePath;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.log.SamsungAnalyticsLog;
import com.sec.android.app.myfiles.module.abstraction.AbsContentObserverImp;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationManager;
import com.sec.android.app.myfiles.util.FileUtils;
import com.sec.android.app.myfiles.util.StorageMonitor;
import com.sec.android.app.myfiles.util.UiUtils;
import com.sec.android.app.myfiles.util.securefolder.HideUtils;
import com.sec.android.app.myfiles.util.securefolder.SecureConstants;

import java.util.ArrayList;
import java.util.Locale;

public abstract class HomeFragmentItem {

    private static final String TAG = HomeFragmentItem.class.getSimpleName() + "-HYL";

    protected Context mContext;
    protected View mRootView;
    protected AbsMyFilesFragment mFragment;

    protected ArrayList<HomeItemInfo> mItemList;
    protected boolean mIsEnabled = true;


    public class HomeItemInfo {
        public View itemView;
        public int resIcon;
        public int resIconColor;
        public int resBgColor;
        public int resString;
        public HomeItemClickListener onClickListener;

        public HomeItemInfo(int stubId, int viewId, int iconId, int iconColorId, int bgColorId, int stringId, HomeItemClickListener onListener) {
            this(stubId, viewId, iconId, iconColorId, bgColorId, onListener);
            resString = stringId;
        }

        public HomeItemInfo(int stubId, int viewId, int iconId, int iconColorId, int bgColorId, HomeItemClickListener onListener) {
            if (mRootView != null) {
                ViewStub stub = null;
                if (stubId != 0) {
                    stub = (ViewStub) mRootView.findViewById(stubId);
                }
                if (stub != null) {
                    itemView = stub.inflate();
                } else {
                    itemView = mRootView.findViewById(viewId);
                    setViewVisibility(itemView, View.VISIBLE);
                }
                if ((stubId != 0 && stub != null) || stubId == 0) {
                    if (itemView != null) {
                        TextView sizeView = (TextView) itemView.findViewById(R.id.home_list_item_text_second);
                        UiUtils.limitLargeTextSize(mContext, sizeView);
                    }
                }
                resIcon = iconId;
                resIconColor = iconColorId;
                resBgColor = bgColorId;
                onClickListener = onListener;
            }
        }

        public String getDisplayText() {
            return mContext.getResources().getString(resString);
        }
    }

    public class HomeUsbItemInfo extends HomeItemInfo {
        String usbName;

        public HomeUsbItemInfo(int stubId, int viewId, int iconId, int iconColorId, String resName, HomeItemClickListener onListener) {
            super(stubId, viewId, iconId, iconColorId, 0, onListener);
            usbName = resName;
        }

        @Override
        public String getDisplayText() {
            return usbName;
        }
    }

    public class HomeItemClickListener implements OnClickListener {
        private FileRecord mRecord;
        private String mLoggingString;

        public HomeItemClickListener(FileRecord record, String loggingString) {
            mRecord = record;
            mLoggingString = loggingString;
        }

        public void setFileRecord(FileRecord fileRecord) {
            mRecord = fileRecord;
        }

        @Override
        public void onClick(View view) {
            if (view == null || view.getVisibility() != View.VISIBLE) {
                Log.e(this, "view is invalid");
                return;
            }

            boolean needClear = false;
            if (R.id.home_recent_item == view.getId()) {
                needClear = true;
            }

            enter(mRecord, needClear);
        }
    }

    public void enter(FileRecord record, boolean needClear) {
        NavigationManager navigationMgr = NavigationManager.getInstance(mFragment.getProcessId());
        NavigationInfo curInfo = navigationMgr.getCurInfo();

        if ((curInfo != null) && (record != null)) {
            Log.i(TAG, "onClick : " + record.getName() + ", isRoot ? " + record.isRoot() + ", recordpath: " + record.getFullPath());
            /**
             * If cur record is same, do not enter
             */
            if (!record.equals(curInfo.getCurRecord())) {

                /*
                //TODO HYL 临时修改 点击root时跳转到SecureFileListFragment
                if (record.getFullPath().startsWith(StoragePath.INTERNAL_ROOT)) {
					//TODO 临时修改 
					
					//初始化根目录
					HideUtils hideUtils = HideUtils.getInstance(mContext);
					hideUtils.initPrivateRecovery();
					hideUtils.mkTestFiles();
					
					//修改跳转路径
					record.setPath(SecureConstants.privateRecoveryRootPath);
					
					//修改StorageType 为 SecureLocal
					record.setStorageType(FileRecord.StorageType.SecureLocal);
					
                }
                //TODO HYL END
                */

                NavigationInfo navigationInfo = NavigationInfo.getInstance(curInfo, record);

                if (navigationInfo != null) {
                    surveyLog(record, curInfo, navigationInfo);
                    curInfo.setFocusRecord(record);
                    if (needClear) {
                        Log.e(this, "onClick - home_recent_item -> clear");

                        for (int i = 0; i < curInfo.getObserverSize(); i++) {
                            AbsContentObserverImp prevObserver = curInfo.getContentObserver(i);
                            if (prevObserver != null) {
                                prevObserver.stop();
                            }
                        }
                        navigationMgr.clear();
                    }
                    if (NavigationInfo.NavigationMode.Select_optimize_storage_backup_destination.equals(curInfo.getNavigationMode())) {
                        if (record.isRoot()) {
                            String enterPath = record.getName();
                            if (StorageMonitor.isSdCardPath(record.getFullPath())) {
                                enterPath = mContext.getString(R.string.sd_card);
                            }
                            SamsungAnalyticsLog.sendLog(curInfo.getScreenPath(), SamsungAnalyticsLog.Event.BACK_UP_TO, enterPath, null);
                        }
                    }

                    navigationMgr.enter(navigationInfo);
                } else {
                    Log.a(this, "onClick : navigationInfo is null");
                }
            } else {
                // This is test code to check whether record is same with curInfo's curRecord or not
                // because sometimes there is the problem can't be entered into "Device storage"
                if (record.equals(curInfo.getCurRecord())) {
                    Log.a(this, "onClick : record is same with curInfo.getCurRecord ");
                }
            }
        } else {
            Log.a(this, "onClick : curInfo is null or record is null");
        }
    }

    public HomeFragmentItem(Context context, HomeFragment fragment) {
        mContext = context;
        mFragment = fragment;
        mRootView = fragment.getView();
        mItemList = new ArrayList<>();

        setListItem();
        setItemView();
    }

    private void setFocus(HomeItemInfo homeItem) {
        FileRecord focusRecord = getFocusedItem();
        FileRecord record = homeItem.onClickListener.mRecord;

        if (focusRecord != null && focusRecord.equals(record)
                && !(!AppFeatures.isTabletUIMode() && ((FileListActivity) mFragment.getActivity()).isSearchViewExpanded())) {
            homeItem.itemView.requestFocus();
        }
    }

    protected FileRecord getFocusedItem() {
        FileRecord ret = null;
        NavigationManager navigationMgr = NavigationManager.getInstance(mFragment.getProcessId());
        NavigationInfo curInfo = navigationMgr.getCurInfo();
        if (curInfo != null) {
            ret = curInfo.getFocusRecord();
        }
        return ret;
    }

    protected void setItemView(HomeItemInfo homeItem) {
        ImageView iconView = (ImageView) homeItem.itemView.findViewById(R.id.home_list_item_thumbnail);
        if (iconView != null) {
            iconView.setImageResource(homeItem.resIcon);
            iconView.setColorFilter(ContextCompat.getColor(mContext, homeItem.resIconColor));
            setCategoryGridItemBackground(homeItem, iconView);
        }
        TextView textView = (TextView) homeItem.itemView.findViewById(R.id.home_list_item_text);
        textView.setText(homeItem.getDisplayText());
        homeItem.itemView.setOnClickListener(homeItem.onClickListener);
    }

    private void setCategoryGridItemBackground(HomeItemInfo homeItem, ImageView iconView) {
        if (homeItem.resBgColor != 0) {
            GradientDrawable backgroundGradient = (GradientDrawable) iconView.getBackground();
            if (backgroundGradient != null)
                backgroundGradient.setStroke(1, ContextCompat.getColor(mContext, homeItem.resBgColor));
        }
    }

    protected void setItemView() {
        for (HomeItemInfo homeItem : mItemList) {
            setItemView(homeItem);
            setFocus(homeItem);
        }
    }

    protected void setViewVisibility(View view, int visibility) {
        if (view != null) {
            view.setVisibility(visibility);
        }
    }

    private void clearList() {
        if (mItemList != null) {
            mItemList.clear();
            mItemList = null;
        }
    }

    protected void setItemEnabled(boolean enabled) {
        mIsEnabled = enabled;
        if (mItemList != null) {
            for (HomeItemInfo h : mItemList) {
                setChildItemEnabled(h.itemView, enabled);
            }
        }
    }

    protected void setChildItemEnabled(View view, boolean bEnable) {
        if (view != null) {
            float alpha = bEnable ? 1.0f : 0.4f;
            view.setEnabled(bEnable);
            view.setAlpha(alpha);
        }
    }

    private void surveyLog(FileRecord record, NavigationInfo curInfo, NavigationInfo nextInfo) {
        SamsungAnalyticsLog.Event event = SamsungAnalyticsLog.Event.NONE;
        String mDetail = null;
        int processId = mFragment.getProcessId();

        if (record.getFullPath().startsWith(StoragePath.INTERNAL_ROOT)) {
            event = SamsungAnalyticsLog.Event.INTERNAL_STORAGE;
            mDetail = "Internal storage";
            Handler mHandler = new Handler(Looper.getMainLooper());
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    sendMemLog(mFragment.getProcessId());
                }
            }, 0);
        } else if (StorageMonitor.isMountedSdCardPath(record.getFullPath())) {
            event = SamsungAnalyticsLog.Event.SD_CARD;
            mDetail = "SD card";
        } else if (record.getFullPath().startsWith(StoragePath.CATEGORY_IMAGE)) {
            event = SamsungAnalyticsLog.Event.CATEGORY_IMAGES;
            mDetail = "Images";
        } else if (record.getFullPath().startsWith(StoragePath.CATEGORY_VIDEO)) {
            event = SamsungAnalyticsLog.Event.CATEGORY_VIDEOS;
            mDetail = "Videos";
        } else if (record.getFullPath().startsWith(StoragePath.CATEGORY_AUDIO)) {
            event = SamsungAnalyticsLog.Event.CATEGORY_AUDIO;
            mDetail = "Audio";
        } else if (record.getFullPath().startsWith(StoragePath.CATEGORY_DOCUMENT)) {
            event = SamsungAnalyticsLog.Event.CATEGORY_DOCUMENT;
            mDetail = "Documents";
        } else if (record.getFullPath().startsWith(StoragePath.DOWNLOADS)) {
            event = SamsungAnalyticsLog.Event.CATEGORY_DOWNLOAD;
            mDetail = "Downloads";
        } else if (record.getFullPath().startsWith(StoragePath.CATEGORY_APK)) {
            event = SamsungAnalyticsLog.Event.CATEGORY_INSTALLATION_FILES;
            mDetail = "Installation files";
        } else if (StorageMonitor.startWithUsbRoot(record.getFullPath())) {
            event = SamsungAnalyticsLog.Event.USB_STORAGE;
            mDetail = "USB storage";
        } else if (record.getFullPath().startsWith(StoragePath.SAMSUNG_DRIVE_FOLDER)) {
            event = SamsungAnalyticsLog.Event.SAMSUNG_CLOUD_DRIVE;
            mDetail = "Samsung Cloud Drive";
        } else if (record.getFullPath().startsWith(StoragePath.GOOGLE_DRIVE_FOLDER)) {
            event = SamsungAnalyticsLog.Event.GOOGLE_DRIVE;
            mDetail = "Google Drive";
        } else if (record.getFullPath().startsWith(StoragePath.RECENT_FILES)) {
            event = SamsungAnalyticsLog.Event.EXTENDS_RECENT_FILES;
            mDetail = "Recent files";
        }
        if (!curInfo.isSelectOpDestination() && !curInfo.isPickerMode()) {
            nextInfo.setScreenPath(UiUtils.getScreenPathFromRecord(record));
        }

        if (curInfo.isSelectOpDestination()) {
            if (curInfo.getNavigationMode() == NavigationInfo.NavigationMode.Select_move_destination) {
                event = SamsungAnalyticsLog.Event.MOVE_TO;
            } else if (curInfo.getNavigationMode() == NavigationInfo.NavigationMode.Select_copy_destination) {
                event = SamsungAnalyticsLog.Event.COPY_TO;
            }
        } else if (event.equals(SamsungAnalyticsLog.Event.GOOGLE_DRIVE)) {
            mDetail = CloudMgr.getInstance(mContext).isSignedIn(FileRecord.CloudType.GoogleDrive) ? "1" : "0";
        } else if (event.equals(SamsungAnalyticsLog.Event.SAMSUNG_CLOUD_DRIVE)) {
            mDetail = CloudMgr.getInstance(mContext).isSignedIn(FileRecord.CloudType.SamsungDrive) ? "1" : "0";
        } else if (!curInfo.isPickerMode()) {
            mDetail = null;
        }
        SamsungAnalyticsLog.sendLog(processId, event, mDetail, null);
    }

    private void sendMemLog(final int procId) {
        String storageInfo = String.format(Locale.US, "Music : %d/%.2fMB, Videos : %d/%.2fMB, Pictures : %d/%.2fMB, Space : %.2fMB/%.2fMB",
                FileUtils.getPhoneMemoryInfo(mContext, MediaStore.Files.FileColumns.MEDIA_TYPE_AUDIO, false), FileUtils.getPhoneMemoryInfo(mContext, MediaStore.Files.FileColumns.MEDIA_TYPE_AUDIO, true) / (double) FileUtils.MEGA_BYTES,
                FileUtils.getPhoneMemoryInfo(mContext, MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO, false), FileUtils.getPhoneMemoryInfo(mContext, MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO, true) / (double) FileUtils.MEGA_BYTES,
                FileUtils.getPhoneMemoryInfo(mContext, MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE, false), FileUtils.getPhoneMemoryInfo(mContext, MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE, true) / (double) FileUtils.MEGA_BYTES,
                StorageMonitor.getStorageFreeSpace(mContext, StorageMonitor.iStorageType.INTERNAL) / (double) FileUtils.MEGA_BYTES,
                StorageMonitor.getStorageSize(mContext, StorageMonitor.iStorageType.INTERNAL) / (double) FileUtils.MEGA_BYTES);

        Log.d(this, "getPhoneMemoryInfo : " + storageInfo);
        SamsungAnalyticsLog.sendLog(procId, SamsungAnalyticsLog.Event.INTERNAL_STORAGE_USAGE, storageInfo, null);
    }

    public final void onPause() {
        _onPause();
    }

    public final void onResume() {
        _onResume();
    }

    public final void onDestroy() {
        clearList();
        _onDestroy();
    }

    protected abstract void setListItem();

    protected void setContentDescription(TextView header, int stringId) {
        if (UiUtils.isTalkBackEnabled(mContext)) {
            if (header != null) {
                header.setContentDescription(UiUtils.getHomeDescription(mContext, stringId, R.string.tts_header));
            }
        }
    }

    protected abstract void _onPause();

    protected abstract void _onResume();

    protected abstract void _onDestroy();

    public interface SelectableItem {
        public void setCheckMode(boolean checkMode);

        public void selectAll();

        public void unselectAll();

        public ArrayList<FileRecord> getSelectedFile();
    }
}
